<template>
    <div>
        <!-- :auto-upload="false" -->

        <el-upload ref="upload" :limit="1" :action="fileUploadApi + '/pictures'" :headers="headers" :on-error="handleError" accept="image/jpeg,image/gif,image/png" class="myuploader" :show-file-list="false"
            :on-success="handleUploadSuccess" :before-upload="beforeUpload"
>
            <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" /> -->
            <!--
        :preview-src-list="[imageUrl]"
                fit="contain"
        -->
            <el-image v-if="imageUrl" :src="imageUrl" lazy class="avatar">
                <div slot="error">
                    <el-tooltip class="item" effect="dark" :content="'图片不存在：' + imageUrl + '，请上传一张图片格式文件'" placement="bottom">
                        <i class="el-icon-plus uploader-icon"> 重新上传图片 </i>
                    </el-tooltip>
                </div>
            </el-image>
            <div v-else>
                <i class="el-icon-plus uploader-icon"> 上传图片 </i>
                <div slot="tip" class="el-upload__tip">请上传一张图片格式文件</div>
            </div>
        </el-upload>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

export default {
  model: {
    prop: 'imageUrl',
    event: 'picUploaded'
  },
  props: {
    imageUrl: { type: String, default: '' }
  },
  data() {
    return {
      headers: { Authorization: getToken() }
    }
  },
  computed: {
    ...mapGetters(['baseApi', 'fileUploadApi'])
  },
  methods: {
    handleUploadSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)

      this.imageUrl = this.baseApi + '/file/' + res.type + '/' + res.realName
      console.log(this.imageUrl)
      this.$emit('picUploaded', this.imageUrl)
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPGGIFPNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isJPG && isLt2M
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>
.myuploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.myuploader .el-upload:hover {
    border: 2px dashed;
    border-color: #409eff;
}
.uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
